package com.urbanski.clipboard.client.action;

import java.io.IOException;
import org.apache.log4j.Logger;
import com.urbanski.clipboard.client.ClipboardClient;
import com.urbanski.clipboard.client.ServerConnection;
import com.urbanski.clipboard.client.util.ClientConstants.ClientCommand;
import com.urbanski.clipboard.common.message.LeaveMessage;
import com.urbanski.clipboard.common.message.Response;
import com.urbanski.util.logging.LoggingUtil;

public class LeaveActionHandler extends ClientActionHandler
{
	private static final Logger LOGGER = Logger.getLogger(LeaveActionHandler.class);

	private String server;
	private String session;

	public LeaveActionHandler(String[] tokens)
	{
		super(ClientCommand.LEAVE, tokens);
	}

	@Override
	public void execute()
	{
		processArgs();

		if (server != null && session != null)
		{
			ServerConnection serverConnection = ClipboardClient.findConnection(server);
			if (serverConnection == null)
			{
				LoggingUtil.logAndPrintError(LOGGER, "No active connection with name " + server);
			}
			else
			{
				LeaveMessage message = new LeaveMessage(session);
				Response response;
				try
				{
					response = serverConnection.sendMessage(message);
					LoggingUtil.logAndPrintInfo(LOGGER, response.getResponseText());
				}
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
	}

	private void processArgs()
	{
		if (tokens.length != 3)
		{
			LoggingUtil.logAndPrintError(LOGGER, "Invalid number of arguments for leave command");
			return;
		}

		server = tokens[1];
		session = tokens[2];
	}

}
